package cn.changeforyou.web.dao.mybatis.ext.accessScene;

import cn.changeforyou.web.dao.mybatis.ext.metaInfo.MappedStatementMetaInfo;
import cn.changeforyou.web.dao.mybatis.ext.metaInfo.parser.MappedStatementMetaInfoHolder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.*;

@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
})
@Component
public class ResultMapInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (!(invocation.getTarget() instanceof Executor)) {
            return invocation.proceed();
        }
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];

        // xml sql 不做处理
        if (ms.getResource().contains(".xml")) {
            return invocation.proceed();
        }

        //带了ResultMap的不管
        ResultMap resultMap = ms.getResultMaps().iterator().next();
        if (!CollectionUtils.isEmpty(resultMap.getResultMappings())) {
            return invocation.proceed();
        }

        //根据Type构建新的ResultMap
        if (MappedStatementMetaInfoHolder.isOursMappedStatementId(ms.getId())) {
            MappedStatementMetaInfo mappedStatementMetaInfo = MappedStatementMetaInfoHolder.getOrCreateMappedStatementMetaInfoInInterceptor(ms, invocation.getArgs()[1]);
            Class resultType = mappedStatementMetaInfo.getResultType();
            if(null != resultType) {
                resultMap = new ResultMap.Builder(ms.getConfiguration(), resultMap.getId(), resultType, new ArrayList<>()).build();
                Field field = ReflectionUtils.findField(MappedStatement.class, "resultMaps");
                ReflectionUtils.makeAccessible(field);
                ReflectionUtils.setField(field, ms, Collections.singletonList(resultMap));
            }
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}